package cn.springmvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.springmvc.exception.SessionTimeoutException;
import cn.springmvc.model.SysUser;
import org.springframework.web.servlet.ModelAndView;

import cn.springmvc.comm.GlobalConstants;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

/**
 * Session超时拦截器
 *
 */
public class SessionTimeoutInInterceptor extends HandlerInterceptorAdapter {

	public String[] allowUrls;//还没发现可以直接配置不拦截的资源，所以在代码里面来排除

	public void setAllowUrls(String[] allowUrls) {
		this.allowUrls = allowUrls;
	}

	// preHandle()方法在业务处理器处理请求之前被调用
	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response, Object handler) throws Exception {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");

		String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
//		System.out.println("========================="+requestUrl);

		boolean beFilter = true;
		if (null != allowUrls && allowUrls.length >= 1) {
			for (String url : allowUrls) {
				if (requestUrl.contains(url)) {
					beFilter = false;
					break;
				}
			}
		}

		if (beFilter) {
			SysUser use =(SysUser)WebUtils.getSessionAttribute(request,GlobalConstants.SESSION_LOGIN_USER);
			if (null == use) {
				if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) { //如果是ajax请求响应头会有，x-requested-with
					response.setHeader("sessionstatus", "timeout");//在响应头设置session状态
					return true;
				}
				// 未登录跳转到登录页面
				throw new SessionTimeoutException();//返回到配置文件中定义的路径
			}
		}
		return super.preHandle(request,response,handler);
	}

//
//	}

	// postHandle()方法在业务处理器处理请求之后被调用
	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
//		System.out.println("22222");
	}

	// afterCompletion()方法在DispatcherServlet完全处理完请求后被调用
	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
//		System.out.println("33333");
	}
}
